package com.example.servlettemplate.servlet;

import com.example.servlettemplate.dao.UserDAO;
import com.example.servlettemplate.pojo.User;
import com.example.servlettemplate.util.RequestUtil;


import com.example.servlettemplate.util.SystemConstants;
import com.mysql.cj.protocol.x.XMessage;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;


@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private UserDAO userDAO = new UserDAO();

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = RequestUtil.getString(req, "username");
        if (username == null) {
            error("用户名不能为空", req, resp);
            return;
        }
        String password = RequestUtil.getString(req, "password");
        if (password == null) {
            error("密码不能为空", req, resp);
            return;
        }
        User user = userDAO.getUserByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            error("用户名或密码错误", req, resp);
            return;
        }
        HttpSession session = req.getSession();
        user.setPassword(null);
        session.setAttribute(SystemConstants.SESSION_USER, user);
        //如果登录成功，跳转首页
        resp.sendRedirect(req.getContextPath() + "/page?act=index");
    }

    public void error(String message, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setAttribute("message", message);
        req.getRequestDispatcher(SystemConstants.PAGE_PATH + "login.jsp").forward(req, resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
